# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: socket_pipe.py 
@time: 2019/7/23 上午9:59
@note:进程间传递Socket文件描述符
"""
import multiprocessing
from multiprocessing.reduction import recv_handle, send_handle
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR


def worker(in_p, out_p):

    out_p.close()

    while True:
        fd = recv_handle(in_p)
        print('CHILD: GOT FD', fd)
        with socket(AF_INET, SOCK_STREAM, fileno=fd) as s:
            while True:
                msg = s.recv(1024)
                if not msg:
                    break
                print('CHILD: RECV {!r}'.format(msg))
                s.send(msg)

def server(address, in_p, out_p, worker_pid):

    in_p.close()
    s = socket(AF_INET, SOCK_STREAM)
    s.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
    s.bind(address)
    s.listen(1)

    while True:
        client, addr = s.accept()
        print("SERVER: Got connection from", addr)
        send_handle(out_p, client.fileno(), worker_pid)
        client.close()


if __name__ == '__main__':

    c1, c2 = multiprocessing.Pipe()
    worker_p = multiprocessing.Process(target=worker, args=(c1, c2))
    worker_p.start()

    server_p = multiprocessing.Process(target=server, args=(('', 15000), c1, c2, worker_p.pid))
    server_p.start()

    c1.close()
    c2.close()

# Example usage
"""
open Terminal

telnet localhost 15000
"""
